<template>
	<div class="header-menus">
		<div class="cpnt-lib-searcher">
			<el-autocomplete
				v-model="state.searchText"
				:fetch-suggestions="querySearchAsync"
				placeholder="请输入组件名称进行搜索"
				value-key="name"
				clearable
				popper-class="cpnt-lib-autocomplete"
				:popper-append-to-body="true"
				@select="handleSearchSelect">
				<template #prefix>
					<el-icon><Search /></el-icon>
				</template>
			</el-autocomplete>
		</div>
		<!-- <div class="cif-configurator-logo">
			<div class="wrench-logo">
				<img :src="wrenchLogo" />
			</div>
			<div class="menu-title">可视化应用配置</div>
		</div> -->
		<div class="divider-h" />
		<el-menu
			ref="cpntlibmenu"
			:default-active="state.activeIndex"
			class="cif-menu-demo"
			mode="horizontal"
			menu-trigger="click"
			:unique-opened="true"
			@select="handleSelect">
			<template v-for="(subMenu, index) in state.cpntLibMenus">
				<el-sub-menu
					v-if="subMenu.length !== 0"
					:key="`menu-item-${index}`"
					:index="`${index}`"
					popper-class="cif-header-menus-popper">
					<template #title>
						{{ state.cpntLibClassification[index] }}
					</template>
					<el-menu-item
						v-for="cpntLibEntry in subMenu"
						:id="cpntLibEntry.id"
						:key="cpntLibEntry.id"
						:index="cpntLibEntry.id"
						:class="cpntLibEntry.name === state.searchText ? 'matched' : ''">
						<div class="cpnt-card-content">
							<div class="cpnt-card-header">
								<span class="name">
									{{ cpntLibEntry.name }}
									<span class="version">v{{ cpntLibEntry.version }}</span>
								</span>
								<span
									class="cpnt-type"
									:aria-label="state.cpntTypeHint[cpntLibEntry.cpntType || 2]"
									:title="state.cpntTypeHint[cpntLibEntry.cpntType || 2]">
									{{ state.cpntTypeName[cpntLibEntry.cpntType || 2] }}
								</span>
							</div>
							<div class="cpnt-image">
								<img :src="`/api/sys-storage/download_image?f8s=${cpntLibEntry.thumbnail}`" />
							</div>
						</div>
					</el-menu-item>
				</el-sub-menu>
				<el-menu-item v-else :key="`disalbe-item-${index}`" :index="`${index}`" disabled>
					{{ state.cpntLibClassification[index] }}
				</el-menu-item>
			</template>
		</el-menu>
		<div class="divider-h" />
		<div class="cif-menu-action-logo">
			<div
				v-if="isShowSaveBtn"
				class="save-logo"
				aria-label="保存应用配置"
				title="保存应用配置"
				@click="saveAppAndExit">
				<img :src="saveLogo" />
			</div>
		</div>
	</div>
</template>

<script setup>
import { onMounted, reactive, toRefs, ref, computed } from 'vue';
import {
	ComponentTreeHelper,
	ComponentTreeNodeTypeEnum
} from '@CIF/ComponentTemplate/componentTree';
import StorageHelper from '@CIF/Runtime/Global/storage';
import { RUNTIME_CFG_ENUM } from '@CIF/Runtime/Global/variable';
import { ElMessage } from 'element-plus';
import { usePrimaryStore } from '@/store';
import * as CIF_API from '@CIF/API/api.js';
import _ from 'lodash';
import saveLogo from '@CIF/Runtime/assets/save.svg';

const store = usePrimaryStore();
const state = reactive({
	activeIndex: '1',
	cpntLibClassification: ['系统组件', '基础组件', '分析组件', '服务组件', '未分类组件'],
	cpntLibMenus: [],

	saveLogo,

	searchText: '',

	cpntTypeName: ['普通', '容器', '未知'],
	cpntTypeHint: ['普通类型组件', '容器类型组件，选中可添加子组件', '组件类型未知']
});
const isShowSaveBtn = computed(() => {
	return StorageHelper.get(RUNTIME_CFG_ENUM.CIF_MODE) === RUNTIME_CFG_ENUM.EDIT_MODE;
});
const cpntTreeData = computed(() => {
	return store.getCpntTree;
});
const restaurants = ref([]);
function generateCpntLibMenu() {
	const cpntLibMenus = [];
	state.cpntLibClassification.forEach(() => {
		cpntLibMenus.push([]);
	});
	const cpntLibs = StorageHelper.get(RUNTIME_CFG_ENUM.COMPONENT_LIBRARY);
	// console.log('-----------cpntLibs', cpntLibs);
	restaurants.value = cpntLibs;
	// let i = 0;
	// for (i = 0; i < cpntLibs.length; i++) {
	// 	const cpntLibEntry = cpntLibs[i];
	// 	let j = 0;
	// 	for (j = 0; j < state.cpntLibClassification.length; j++) {
	// 		const classif = state.cpntLibClassification[j];
	// 		if (cpntLibEntry.classification === classif) {
	// 			cpntLibMenus[j].push(cpntLibEntry);
	// 		}
	// 	}
	// }
	for (const cpntLibEntry of cpntLibs) {
		const classif = state.cpntLibClassification.find((c) => c === cpntLibEntry.classification);
		if (classif) {
			const index = state.cpntLibClassification.indexOf(classif);
			cpntLibMenus[index].push(cpntLibEntry);
		}
	}
	state.cpntLibMenus = cpntLibMenus.map((x) => {
		return _.orderBy(x, ['cpntType', 'name'], ['desc', 'asc']);
	});
	console.log('------------cpntLibMenus', state.cpntLibMenus);
}
generateCpntLibMenu();
// 搜索框相关
function querySearchAsync(queryString, cb) {
	const results = queryString
		? restaurants.value.filter(createStateFilter(queryString))
		: restaurants.value;
	cb(results);
}
function createStateFilter(queryString) {
	return (restaurant) => {
		return (
			restaurant.value && restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
		);
	};
}
const cpntlibmenu = ref();
function handleSearchSelect(item) {
	// console.log(item);
	let index = -1;
	for (let i = 0; i < state.cpntLibClassification.length; i++) {
		if (state.cpntLibMenus[i].length === 0) {
			index += 1;
			continue;
		}
		index += 1;
		if (item.classification === state.cpntLibClassification[i]) {
			break;
		}
	}
	cpntlibmenu.value.open(index);
	// 自动滚动到相应位置，代码有待优化
	// setTimeout(() => {
	// 	window.headerMeuScrollInst[index].scroll(document.getElementById(item.id), 800);
	// }, 300);
	setTimeout(() => {
		document.getElementById(item.id).scrollIntoView({ behavior: 'smooth', block: 'start' });
	}, 300);
}

function handleSelect(key) {
	// const cpntTreeData = StorageHelper.get(RUNTIME_CFG_ENUM.APPLICATION_COMPONENT_TREE);
	const treeNodeInfoList = store.getSelectedCpntTreeNodeInfo;
	// console.log('treeNodeInfoList-----------------', treeNodeInfoList);
	const parentNode =
		treeNodeInfoList.filter((x) => x.type !== ComponentTreeNodeTypeEnum.FOLDER)[0] || {};
	const parentId = parentNode.type === ComponentTreeNodeTypeEnum.NORMAL ? '' : parentNode.id;
	ComponentTreeHelper.addNewInstancesToTreeByDefIds(cpntTreeData.value, [key], parentId);
	// console.log('-------------cpntTreeData', cpntTreeData.value);
	store.updateTree(cpntTreeData.value);
	state.activeIndex = null;
}

// 保存相关
function closeWebPage() {
	// !需要配合 window.open() 方法使用
	if (navigator.userAgent.indexOf('MSIE') > 0) {
		//close IE
		if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
			window.opener = null;
			window.close();
		} else {
			window.open('', '_top');
			window.top.close();
		}
	} else if (navigator.userAgent.indexOf('Firefox') > 0) {
		//close firefox
		window.location.href = 'about:blank ';
	} else {
		//close chrome;It is effective when it is only one.
		window.opener = null;
		window.open('', '_self');
		window.close();
	}
}
function generateCountDown() {
	setTimeout(() => {
		closeWebPage();
	}, 3000);
}
function saveAppAndExit() {
	const cifMode = StorageHelper.get(RUNTIME_CFG_ENUM.CIF_MODE);
	if (cifMode === RUNTIME_CFG_ENUM.EDIT_MODE) {
		const appCpntTree = StorageHelper.get(RUNTIME_CFG_ENUM.APPLICATION_COMPONENT_TREE);
		const formData = {
			id: StorageHelper.get(RUNTIME_CFG_ENUM.APPLICATION_ID),
			componentTree: ComponentTreeHelper.saveTree(appCpntTree),
			referenceComponent: JSON.stringify(
				StorageHelper.get(RUNTIME_CFG_ENUM.APPLICATION_REFRENCE_COMPONENT_CFG)
			)
		};
		CIF_API.updateApplicationConfiguration(formData)
			.then((res) => {
				if (res.status) {
					// ElMessage.success(res.message)
					ElMessage.success('应用组件配置保存成功, 本页面将在3s后自动关闭!');
					generateCountDown();
				} else {
					ElMessage.error(res.message);
				}
				// this.$emit('setLockStatus', false)
			})
			.catch((e) => {
				console.log(e);
				// this.$emit('setLockStatus', false)
			});
	}
}

onMounted(() => {});
defineExpose({ ...toRefs(state) });
</script>

<style lang="scss">
.cpnt-lib-autocomplete {
	border-color: var(--primary-overlay) !important;
	background-color: rgba(0, 0, 0) !important;
	.el-autocomplete-suggestion__list {
		li {
			color: white;
			&:hover {
				background-color: var(--primary) !important;
			}
		}
		// background-color: var(--dropdown-background) !important;
		// transform: translateY(10px) !important;
	}
}
.el-menu--horizontal.el-menu--popup-container {
	overflow-y: auto;
	background-color: var(--dropdown-background);
	// 滚动条样式
	&:hover::-webkit-scrollbar {
		background: #3d3f46; /* 滑块颜色 */
	}
	&::-webkit-scrollbar {
		/* 滚动条默认隐藏 */
		background-color: transparent;
		width: 6px; /* 滚动条宽度 */
	}
	&::-webkit-scrollbar-track {
		/* 滚动条轨道样式 */
		background: transparent;
	}

	&::-webkit-scrollbar-thumb {
		/* 滚动条滑块样式 */
		// background: #3d3f46; /* 滑块颜色 */
		border-radius: 3px; /* 滑块圆角 */
	}

	&::-webkit-scrollbar-thumb:hover {
		/* 鼠标悬停在滑块上时样式 */
		background: #55575e; /* 滑块悬停颜色 */
	}
}
.cif-header-menus-popper {
	max-height: max(55vh, 623px);
	box-shadow:
		-5px 5px 10px -4px black,
		5px 5px 10px -4px black;
	border: solid 1px var(--primary-overlay) !important;
	background-color: var(--dropdown-background);

	.el-menu.el-menu--popup {
		display: grid;
		grid-template-columns: repeat(auto-fill, 268px);
		grid-auto-rows: 186px;
		grid-column-gap: 15px;
		grid-row-gap: 15px;
		justify-content: space-evenly;
		align-content: start;
		width: min(834px, 75vw);
		padding: 15px;
		border: none !important;
		box-sizing: content-box;
		background-color: transparent;

		.el-menu-item {
			width: 100%;
			height: 100%;
			padding: 0;
			transition-property: none;
			background-color: unset !important;
			border: solid 1px rgb(255 255 255 / 0%);

			&.matched {
				background-color: unset !important;
				border: solid 1px rgba(8, 240, 220, 0.78);
				box-shadow: rgb(6 206 174 / 78%) 0px 0px 2px 0px;
			}

			&:hover {
				background-color: unset !important;
				border: solid 1px var(--primary-active);
				box-shadow: var(--primary-hover) 0px 0px 2px 0px;
			}

			&.is-active {
				background-color: unset !important;
				transition-property: none;
				border: solid 1px rgb(255 255 255 / 0%);
			}

			.cpnt-card-content {
				width: 100%;
				height: 100%;

				.cpnt-card-header {
					height: 22px;
					line-height: 22px;
					display: flex;
					padding: 6px;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					font-size: 14px;
					font-weight: 700;
					color: white;
					box-sizing: content-box;

					.name {
						flex: 1;
					}

					.version {
						margin-left: 8px;
						font-style: italic;
					}

					.cpnt-type {
						background-color: rgba(90, 93, 94, 0.61);
					}
				}

				.cpnt-image {
					img {
						width: 100%;
						height: 150px;
						object-fit: cover;
					}
				}
			}
		}
	}

	.el-menu::after,
	.el-menu::before {
		display: none !important;
	}
}
</style>
<style lang="scss" scoped>
$layerMgrFontSize: 14px;
$layerMgrTitleHeight: 24px;
$topMenuItemHeight: 52px;

.header-menus {
	height: 100%;
	width: 100%;
	max-height: $topMenuItemHeight;
	font-size: $layerMgrFontSize;
	box-sizing: border-box;
	/* border-bottom: solid 1px var(--primary-high); */
	color: white;
	background-color: var(--dropdown-background);
	box-shadow: #000000 0px 3px 6px 0px;
	display: flex;
	.cpnt-lib-searcher {
		width: 300px;
		display: flex;
		align-items: center;
		padding: 8px;
		box-sizing: border-box;

		:deep(.el-autocomplete) {
			width: 100%;
			.el-input__wrapper {
				background-color: transparent;
				border: 0;
				// border: 1px solid var(--primary);
			}
		}
	}
	.cif-configurator-logo {
		padding: 2px 16px;
		width: 300px;
		height: $topMenuItemHeight;
		box-sizing: border-box;
		display: flex;
		flex-shrink: 0;

		.wrench-logo {
			width: 48px;
			height: 48px;
			padding: 4px;
			box-sizing: border-box;

			img {
				width: 100%;
				height: 100%;
			}
		}
		.menu-title {
			line-height: 48px;
			height: 48px;
			flex: 1;
			padding: 0 4px;
			font-size: 16px;
			font-weight: 700;
		}
	}

	.divider-h {
		height: 100%;
		/* margin: 0 2px; */
		width: 1px;
		background: rgba(255, 255, 255, 0.3);
	}

	:deep(.el-menu) {
		flex: 1;

		&.el-menu--horizontal {
			border: none !important;
			height: $topMenuItemHeight;
			background-color: transparent;
			.el-menu-item {
				height: $topMenuItemHeight;
				line-height: $topMenuItemHeight;
				color: white !important;
			}

			.el-sub-menu .el-sub-menu__title {
				height: $topMenuItemHeight;
				line-height: $topMenuItemHeight;
				color: white !important;
				border-bottom: 2px solid rgba(0, 0, 0, 0);
				&:hover {
					background-color: var(--primary-active);
				}
			}

			.el-sub-menu.is-opened {
				.el-sub-menu__title {
					border-bottom: 2px solid var(--primary) !important;
				}
			}
		}
	}

	.cif-menu-action-logo {
		padding: 8px;
		width: 359px;
		height: $topMenuItemHeight;
		box-sizing: border-box;
		display: flex;
		flex-shrink: 0;
		flex-direction: row-reverse;

		.save-logo {
			width: 36px;
			height: 36px;
			padding: 2px;
			box-sizing: border-box;
			cursor: pointer;

			img {
				width: 100%;
				height: 100%;
			}
		}
	}
}
</style>
